<?php
/**
 * @author guoxiaoyong
 */
namespace frontend\controllers;

use bc\controller\GameController;
use bc\model\mosquito\InfoModel;
use bc\util\Util;
use bc\model\mosquito\LogModel;
use bc\model\mosquito\ShareModel;
use bc\ar\MActiveRecord;
use yii\web\Session;

class MosquitoController extends GameController
{
	protected $device;
	
	protected $uniqid;
	
	protected $user;
	
	protected $shareContent;
	
	protected $shareDesc;
	
	protected $shareUrl = 'http://wx.zhishimama.com/mosquito/index';
	
	
	public function init()
	{
		parent::init ();
		$this->device = Util::getBroswer ();
		if ($this->device == 'wechat')
		{
			$this->wechatAuth ();
		}
		
		$uniqid = $_COOKIE['mosquito_uniqid'];
		
		if($uniqid)
		{
			$this->uniqid = $uniqid;
			$info = new InfoModel();
			$user = $info->getRow(['uniqid' => $uniqid]);
			if($user)
			{
				$this->user = $user;
			}
			else 
			{
				$this->user = $this->createAccount($this->device);
			}
		}
		else 
		{
			$this->user = $this->createAccount($this->device);
		}
		
		
		if($this->user['mosquito_nick_name'])
		{
			
			$this->shareContent = '天啦噜！本宝宝在啪啪大战中坚持了' . $this->user['current_time'] . '秒！你行你来！';
		}
		else 
		{
			$this->shareContent = '是不是持久？啪了才知道！500元现金，紫草膏无门槛送！';
		}
		
		$this->shareDesc = '来啊！啪啪啪！互相伤害啊！';
		
	}
	
	/**
	 * 游戏首页
	 */
	public function actionIndex()
	{
		$view = [];
		
		
		if ($this->device == 'wechat')
		{
			// 生成js sdk签名
			$jsConfig = $this->configJsApi ();
			$appid = $this->wechat ()->appid;
			$secret = $this->wechat ()->secret;
			$view ['share_url'] = $this->shareUrl;
			$view ['share_content'] = $this->shareContent;
			$view ['js_config'] = $jsConfig;
			
		}
		
		$blood = $this->user['blood'];
		
		if($_SESSION['wx_openinfo'])
		{
		    if($this->user['blood'] == 1 && $_SESSION['wx_openinfo']['subscribe'] == 1)
		    {
		        $info = new InfoModel();
		        $info->modify(['blood' => 3], $this->user['id']);
		        $blood = 3;
		    }
		}
		
		
		$wx_openid = $_COOKIE['wx_openid'];
		
		if($wx_openid)
		{
		    $dao = new MActiveRecord();
		    $sql = "select uid, subscribe, wxid from wxch_user where wxid = '{$wx_openid}'";
		    $row = $dao->getDb()->createCommand($sql)->queryOne();
		    
// 		    print_r($row);exit;
		    
		    if($this->user['blood'] == 1 && $row['subscribe'] == 1)
		    {
		        $info = new InfoModel();
		        $info->modify(['blood' => 3], $this->user['id']);
		        $blood = 3;
		    }
		    else if($this->user['blood'] == 3 && $row['subscribe'] == 0)
		    {
		        $info = new InfoModel();
		        $info->modify(['blood' => 1], $this->user['id']);
		        $blood = 1;
		    }
		   
		}
		
		
		//分享内容
		if($this->user['mosquito_nick_name'])
		{
			$shareContent = $this->shareContent;
			if($this->device != 'wechat')
			{
				$shareContent .= '微博加：戳这里http://weibo.com/5928035261/DDGvdqqEY';
			}
		}
		else//未参加过游戏
		{
			$shareContent = $this->shareContent;
		}
		
		
		$view['share_content'] = $shareContent;
		$view['share_desc'] = $this->shareDesc;
		$view['device'] = $this->device;
		$view['user'] = $this->user;
		$view['blood'] = $blood;
		
		return $this->render('index', $view);
	}
	
	/**
	 * 排行榜页
	 */
	public function actionTop()
	{
		if ($this->device == 'wechat')
		{
			// 生成js sdk签名
			$jsConfig = $this->configJsApi ();
			$appid = $this->wechat ()->appid;
			$secret = $this->wechat ()->secret;
			$view ['share_url'] = $this->shareUrl;
			$view ['share_content'] = $this->shareContent;
			$view ['js_config'] = $jsConfig;
		}
		
		$type = $this->get ( 'type', 1 );
		
		if($type == 1)//时间
		{
			$sort = 'max_time DESC, create_time ASC';
		}
		else//总共打死的蚊子数 
		{
			$sort = 'total_num DESC, create_time ASC';
		}
		
		$params = 'is_play = 1';
		
		$info = new InfoModel();
		$info->sort = $sort;
		$list = $info->getList($params);
		$total = $info->getTotal($params);
		
		
		$topNumber = 0;
		
		foreach ($list as $key=>&$item)
		{
			if($item['uniqid'] == $this->uniqid)
			{
				$item['self'] = true;
				$topNumber = $key + 1;
			}
			else 
			{
				$item['self'] = false;
			}
		}
		
		$view['type'] = $type;
		$view['total'] = $total;
		$view['list'] = $list;
		
		
		if($topNumber > 0)
		{
			$proportion = $this->proportion($topNumber, $total) . '%';
			$view['top_number'] = $topNumber;
		}
		
		//分享内容
		if($this->user['mosquito_nick_name'])
		{
			$shareContent = $this->shareContent;
			if($this->device != 'wechat')
			{
				//http://weibo.com/5928035261/DDGvdqqEY
				$shareContent .= '微博加：戳这里http://weibo.com/5928035261/DDGvdqqEY';
			}
		}
		else//未参加过游戏
		{
			$shareContent = $this->shareContent;
		}
		
		$view['share_desc'] = $this->shareDesc;
		$view['share_content'] = $shareContent;
		$view['device'] = $this->device;
		
		return $this->render ( 'top', $view );
	}
	
	
	/**
	 * 奖品页 
	 */
	public function actionGift()
	{
		if ($this->device == 'wechat')
		{
			// 生成js sdk签名
			$jsConfig = $this->configJsApi ();
			$appid = $this->wechat ()->appid;
			$secret = $this->wechat ()->secret;
			$view ['share_url'] = $this->shareUrl;
			$view ['js_config'] = $jsConfig;
		}
		
		
		//分享内容
		if($this->user['mosquito_nick_name'])
		{
			$shareContent = $this->shareContent;
			if($this->device != 'wechat')
			{
				$shareContent .= '微博加：戳这里http://weibo.com/5928035261/DDGvdqqEY';
			}
			
		}
		else//未参加过游戏
		{
			$shareContent = $this->shareContent;
		}
		
		$view['share_desc'] = $this->shareDesc;
		$view['share_content'] = $shareContent;
		$view['device'] = $this->device;
		
		$view ['js_config'] = $jsConfig;
		return $this->render ( 'gift', $view );
	}
	
	
	/**
	 * ajax昵称
	 */
	public function actionAjaxnickname()
	{
		$msg = [];
		$msg['error'] = 1;
		$nickname = $this->post('nickname');
		$uniqid = $this->uniqid;
		
		if($nickname)
		{
			$info = new InfoModel();
			$row = $info->getRow(['mosquito_nick_name' => $nickname]);
			if($row)
			{
				$msg['message'] = '该宝宝昵称已存在！';
			}
			else 
			{
				$user = $info->getRow(['uniqid' => $this->uniqid]);
				$data['mosquito_nick_name'] = $nickname;
				$data['is_play'] = 1;
				$info->modify($data, $user['id']);
				$msg['error'] = 0;
			}
		}
		
		echo json_encode($msg);
		exit;
		
	}
	
	
	/**
	 * 更新玩家游戏数据
	 */
	public function actionUpdate()
	{
		
		exit;
		$time = $this->post('time');
		$number = $this->post('number');
		
		$log = new LogModel();
		$uid = $this->user['id'];
		$data['uid'] = $this->user['id'];
		$data['play_time'] = $time;
		$data['number'] = $number;
		$data['create_time'] = time();
		$log->add($data);
		
		$total_number = $this->user['total_num'] + $number;
		$total_time = $this->user['total_time'] + $time;
		$info = new InfoModel();
		if($time > $this->user['max_time'])
		{
			$info->modify(['max_time' => $time, 'total_num' => $total_number, 'total_time' => $total_time], $this->user['id']);
		}
		else 
		{
			$info->modify(['total_num' => $total_number, 'total_time' => $total_time], $this->user['id']);
			
		}
		
		
		$info->modify(['current_time' => $time], $this->user['id']);
		
		$info2 = new InfoModel();
		
		$params = 'is_play = 1';
		//时间排序
		$info->sort = 'current_time DESC, create_time ASC';
		$list = $info->getList($params);
		$total = $info->getTotal($params);
		$topNumber = 0;
		foreach ($list as $key=>&$item)
		{
			if($item['uniqid'] == $this->uniqid)
			{
				$topNumber = $key + 1;
				break;
			}
		}
		
		//按个数排序
		
		$info2->sort = 'total_num DESC, create_time ASC';
		$list2 = $info2->getList($params);
		$topNumber2 = 0;
		foreach ($list2 as $key2=>&$item2)
		{
			if($item2['uniqid'] == $this->uniqid)
			{
				$topNumber2 = $key2 + 1;
				break;
			}
		}
		
		
		$current = $topNumber <= $topNumber2 ? $topNumber : $topNumber2;
		$proportion = $this->proportion($current, $total); 
		
		$msg['total_number'] = $total_number;
		$msg['proportion'] = $proportion . '%';
		echo json_encode($msg);
		exit;
	}
		
	
	/**
	 * 统计分享
	 */
	public function actionShare()
	{
		$share = new ShareModel();
		$data['page_id'] = $this->post('page_id');
		$data['uniqid'] = $this->uniqid;
		$data['create_time'] = time();
		$share->add($data);
	}
	
	/**
	 * 
	 */
	public function actionSharecontent()
	{
		
		//分享内容
		if($this->user['mosquito_nick_name'])
		{
			$user = new InfoModel();
			$row = $user->getRow(['uniqid' => $this->user['uniqid']]);
			
			$shareContent = '天啦噜！本宝宝在啪啪大战中坚持了' . $row['current_time'] . '秒！你行你来！';
			if($this->device != 'wechat')
			{
			}
		}
		else//未参加过游戏
		{
			$shareContent = '是不是持久？啪了才知道！500元现金，紫草膏无门槛送！';
		}
		
		
		if ($this->device == 'wechat')
		{
			// 生成js sdk签名
			$jsConfig = $this->configJsApi ();
			$appid = $this->wechat ()->appid;
			$secret = $this->wechat ()->secret;
			$view ['share_url'] = $this->shareUrl;
			$view ['js_config'] = $jsConfig;
			
		}
		
		
		$msg['share_content'] = $shareContent;
		$msg['share_desc'] = $this->shareDesc;
		$msg['share_url'] = $this->shareUrl;
		echo json_encode($msg);
		exit;
	}
	
	
	public function actionTest()
	{
		if ($this->device == 'wechat')
		{
			// 生成js sdk签名
			$jsConfig = $this->configJsApi ();
			$appid = $this->wechat ()->appid;
			$secret = $this->wechat ()->secret;
			$view ['share_url'] = $this->shareUrl;
			$view ['js_config'] = $jsConfig;
		}
		
		return $this->render('test', $view);
	}
	
	public function actionAjaxtest()
	{
		$res['error'] = 0;
		$res['message'] = 'ajax 回调';
		
		echo json_encode($res);
		exit;
	}
	
	
	/**
	 * @param int $source
	 * 创建游戏账户
	 */
	private function createAccount($source)
	{
	    $uniqid = uniqid ();
	    $data ['uniqid'] = $uniqid;
	    $data ['blood'] = 1;
	    $data['is_play'] = 0;
	    $subscribe = 0;
	    
	    if($_SESSION['wx_openinfo'])
	    {
	        $wx_openinfo = $_SESSION['wx_openinfo'];
	        $subscribe = $wx_openinfo['subscribe'];
	    }
	    
	    
	    if($source == 'wechat')
	    {
	        $data ['source'] = 1;
	    }
	    else
	    {
	        $data ['source'] = 2;
	    }
	     
	    //wechat
	    if($source == 'wechat')
	    {
	        if($subscribe == 1)
	        {
	            $data ['blood'] = 3;
	        }
	    }
	    $data ['total_time'] = 0.0;
	    $data ['total_num'] = 0;
	    $data ['create_time'] = time ();
	    
	    $info = new InfoModel();
	    $id = $info->add($data);
	    
	    $user = $info->getRowById($id);
	    // 写入cookie
	    setcookie ( 'mosquito_uniqid', $uniqid, time () + 3600 * 24 * 21 );
	    
	    return $user;
	}
	
	
	/**
	 * 百分比=（1-两个排行榜中排行名次较高的名次/总参与人数）*100%
	 * @param int $current 当前排名
	 * @param int $total 总人数
	 */
	private function proportion($current, $total)
	{
		$val = (1 - $current / $total) * 100;
		return number_format($val, 1);
	}
}

